<template>
    <rx-layout>
        <div slot="left" width="250" showButton="true">
            <div style="height: 100%;overflow-y: scroll">
                <rx-category-treeeditor
                    cat-key="DIC"
                    :statisticConfig="statisticConfig"
                    :edit="true"
                    @handSelect="handSelect"
                    :async="true"
                    v-if="isShowManageTree"
                    :isAdmin="isManageToTree"
                    :checkToDel="true"
                ></rx-category-treeeditor>
            </div>
        </div>
        <div slot="center">
            <rx-fit>

                <div slot="toolheader" border="false" foldbtn="false">
                    <div class="table-operator">
                        <a-button-group compact>
                            <a-button icon="plus" v-if="findAuthRight('add')" @click="onAddDic">
                                {{$ti18('rxList.newBtn','新增')}}
                            </a-button>

                            <a-button type="primary" icon="save" @click="onSaveDic">
                                {{$ti18('rxForm.saveBtn','保存')}}
                            </a-button>

                            <a-button type="danger" icon="delete" v-if="findAuthRight('delete')" @click="onRemoveDic">
                                {{$ti18('rxList.delBtn','删除')}}
                            </a-button>
                            <a-dropdown>
                                <a-button>
                                    {{$ti18('rxList.moreBtn','更多')}}
                                    <a-icon type="down"/>
                                </a-button>
                                <a-menu slot="overlay">

                                    <a-menu-item type="primary" @click="genQuerySql"><i
                                        class="iconfont iconsql icstyl"></i>
                                        {{i18n('form.generateSQL','生成查询SQL')}}
                                    </a-menu-item>
                                    <a-menu-item @click="doDeployMenu"><i class="iconfont iconfabu icstyl"></i>
                                        {{i18n('form.publishToMenu','发布至菜单')}}
                                    </a-menu-item>
                                    <a-menu-item key="1" @click="doImport"><i class="iconfont icondaoru"></i>&nbsp;&nbsp;
                                        {{$ti18('rxList.importBtn','导入')}}
                                    </a-menu-item>
                                    <a-sub-menu>
                                        <span slot="title"><i class="iconfont icondaochu"></i>&nbsp;&nbsp;
                                        {{$ti18('rxList.exportBtn','导出')}}</span>
                                        <a-menu-item @click="doExport('0')"><i class="iconfont icondaochu"></i>&nbsp;&nbsp;
                                            {{i18n('list.exportAll','导出当前所有')}}
                                        </a-menu-item>
                                        <a-menu-item @click="doExport('1')"><i class="iconfont icondaochu"></i>&nbsp;&nbsp;
                                            {{i18n('list.exportSelected','导出所选中')}}
                                        </a-menu-item>
                                    </a-sub-menu>
                                </a-menu>
                            </a-dropdown>
                        </a-button-group>
                    </div>
                </div>

                <rx-tree-table
                    ref="dicTable"
                    :columns="columns"
                    ajax-type="get"
                    id-field="dicId"
                    :resultAsTree="true"
                    :bordered="true"
                    :allowRowSelect="true"
                    :multiSelect="true"
                    :activeEditFun="(col,row)=>{return this.findAuthRight('edit');}"
                >
                    <span style="display: flex" @click.stop="" slot="name" slot-scope="{text,record,index,blur}">
                        <rx-input-i18n class="SysDicList-input" emitFunKey="i18Change" @i18Change="i18Change(arguments,record)" v-model="record.name" @blur="onBlurName(index,text,record)"/>
                    </span>
                    <span slot="value" @click.stop="" slot-scope="{text,record,index,blur}">
                        <a-form-item :validateStatus="record.errorStatus?'error':''" class="error-form-item">
                            <a-input v-model="record.value" @blur="blurValue(index,text,record)"/>
                        </a-form-item>
                    </span>
                    <span slot="descp" @click.stop="" slot-scope="{text,record,index,blur}">
                        <a-input v-model="record.descp" @blur="blur(index,'descp',text,record)"/>
                    </span>
                    <span slot="colorConfigs" @click.stop="" slot-scope="{text,record,index,blur}">
                        <div class="rx-colorConfigs">
                          <div class="rx-colorConfigs-name">
                              <span :style="styleName(record)">{{$i18(record.name)}}</span>
                               <my-icon @click="deleteStyle(record)" v-if="styleShow(record)" class="rx-colorConfigs-delete" type="iconicon-test28"></my-icon>
                          </div>
                          <my-icon class="rx-colorConfigs-select" @click="openConfig(record)" type="iconsetup"></my-icon>
                        </div>
                    </span>
                    <span slot="sn" @click.stop="" slot-scope="{text,record,index,blur}">
                        <a-input-number :min="1" v-model="record.sn" @blur="blur(index,'sn',text,record)" style="width:100%"/>
                    </span>
                    <span slot="action" slot-scope="{text,index,record}" class="actionIcons">
                        <span v-if="findAuthRight('delete')" @click="onDel(record)">
                            {{$ti18('rxList.delBtn','删除')}}
                        </span>
                    <span @click="onSave(record)">
                        {{$ti18('rxForm.saveBtn', '保存')}}
                    </span>
                    <template v-if="dataShowType()!='FLAT' ">
                        <span @click="onAddSibling(record)">
                            {{i18n('form.addSibling','添加同级') }}
                        </span>
                        <span @click="addChildDic(record)">
                            {{i18n('form.addChild','添加子级') }}
                        </span>
                    </template>
              </span>
                </rx-tree-table>
            </rx-fit>

        </div>
    </rx-layout>

</template>
<script>
import SysDicApi from '@/api/system/core/sysDic'
import SysDicEdit from './SysDicEdit'
import {RxLayout, RxTreeTable, Util,App} from "@lowcode/jpaas-common-lib";
import RxCategoryTreeeditor from "@/components/redxun/rx-category-treeeditor";
import SysDicSql from "./SysDicSql";
import FormImport from '@/views/modules/form/core/FormImport'
import DialogBox from "../../../../assets/js/DialogBox";
import AppManager from "@/views/modules/share/AppManager";
import SysDicColorConfig from "@/views/modules/system/core/SysDicColorConfig"
import FormSolutionButtonMappingConfig from "@/views/modules/form/core/FormSolutionButtonMappingConfig.vue";


export default {
    name: 'SysDicList',
    mixins:[App,AppManager],
    components: {
        RxCategoryTreeeditor,
        SysDicEdit,
        RxLayout,
        RxTreeTable,
        FormImport
    },
    computed: {
        dicTable() {
            return this.$refs.dicTable;
        },
    },
    data() {
        return {
            // 表头
            columns: [
                {
                    title: this.i18n('form.itemName','项名'),
                    dataIndex: 'name',
                    width: 200,
                    allowCellEdit: false,
                    scopedSlots: {customRender: 'name'}
                },
                {
                    title: this.i18n('form.itemValue','项值'),
                    dataIndex: 'value',
                    width: 160,
                    allowCellEdit: false,
                    scopedSlots: {customRender: 'value'}
                },
                {
                    title: this.i18n('form.itemDescription','项描述'),
                    dataIndex: 'descp',
                    width: 200,
                    allowCellEdit: false,
                    scopedSlots: {customRender: 'descp'}
                },
                {
                    title: this.i18n('form.index','序号'),
                    dataIndex: 'sn',
                    width: 120,
                    allowCellEdit: false,
                    scopedSlots: {customRender: 'sn'}
                },
                {
                    title: this.i18n("form.StyliZe","风格化"),
                    dataIndex: 'colorConfigs',
                    width: 120,
                    allowCellEdit: false,
                    scopedSlots: {customRender: 'colorConfigs'}
                },
                {
                    title: this.$ti18('rxList.action','操作'),
                    width: 180,
                    dataIndex: 'action',
                    scopedSlots: {customRender: 'action'}
                }
            ],
            curTree: {},
            errorList:[],
            idx_: 1,
            statisticConfig: {
                type:"static_system",
                table: "SYS_DIC t",
                field: "TREE_ID_",
                whereConf: []
            },

            i18nDefault:process.env.VUE_APP_LANGUAGE,
            i18nCurrent:"",
        }
    },
    created() {
        this.getCurrentI18n()
        this.isUserManager();
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "sysDic", key);
        },
        handSelect(curRow) {
            this.curTree = curRow;
            let treeId = curRow.treeId;
            let url = SysDicApi.baseUrl + "/getByTreeId?treeId=" + treeId;
            this.dicTable.loadData(url);
        },
        //编辑字典项时，对非空的值进行copy
        onBlurName(index, value, record) {
            if(value){
                let i18Name = JSON.parse(value);
                for(let name in i18Name){
                    i18Name[name] = i18Name[name].trim()
                }
                record.name = JSON.stringify(i18Name)
            }
            if (record.value == '') {
                record.value = this.$i18(record.name);
            }
            if (record.descp == '') {
                record.descp = this.$i18(record.name);
            }
            if (!record.sn) {
                record.sn = index + 1;
            }
        },
        blurValue(index, value, record){
            if(value){
                record.value = value.trim()
            }
        },
        i18Change(data,record){
            record.name=JSON.stringify(data[0])
            console.log(record)
        },
        deleteStyle(record){
            record.colorConfigs="";
            this.onSave(record)
        },
        openConfig(record){
            let config=record.colorConfigs
            if (record.colorConfigs && typeof record.colorConfigs =='string' ){
                config=JSON.parse(record.colorConfigs)
            }
            var conf= {
                curVm:this,
                data:{
                    config:config,
                    name:this.$i18(record.name)
                },
                component:SysDicColorConfig,
                widthHeight: ['523px', '492px'],
                title: this.i18n("form.StyliZeConfig","风格化配置")
            };
            var self_=this;
            Util.open(conf,function(action,data){
                if (action!="ok"){
                    return
                }
               record.colorConfigs=JSON.stringify(data);
               self_.onSave(record)
            })
        },
        catTitle() {
            return this.curTree.name || "选择分类";
        },
        dataShowType() {
            return this.curTree.dataShowType || "FLAT";
        },
        onAddDic() {
            if (!this.curTree.treeId) {
                this.$message.error(this.i18n('isMsg.category','请选择分类','select'));
                return;
            }
            var treeId = this.curTree.treeId;
            if (treeId == "0") {
                this.$message.error(this.i18n('isMsg.rootNode','无法添加到根节点!'));
                return;
            }
            this.dicTable.addNode({dicId: this.idx_++, isAdd: true, appId: this.curApp.appId});
        },
        onDel(record) {
            let self_ = this;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips','操作提示'),
                content: this.$ti18('rxMsa.delInfo','您确定需要删除选中的记录吗？'),
                okText: this.$ti18('rxForm.ackBtn','确认'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    if (record.isAdd) {
                        self_.dicTable.removeNode(record);
                        return;
                    }
                    SysDicApi.delByDicId(record['dicId'], record['treeId']).then(res => {
                        self_.dicTable.removeNode(record);
                    })
                },
                onCancel() {
                }
            })
        },
        addChildDic(record) {
            if (!record.children) {
              this.$set(record,'children',[]);
            }
            this.dicTable.addNode({
                dicId: this.idx_++,
                isAdd: true,
                parentId: record['dicId'],
                appId: this.curApp.appId
            }, record);
            this.$forceUpdate()
        },
        onAddSibling(record) {
            if (record.parentId && record.parentId != '0') {
                var parentNode = this.dicTable.getParentNode(record);
                this.dicTable.addNode({
                    dicId: this.idx_++,
                    isAdd: true,
                    parentId: parentNode['dicId'],
                    appId: this.curApp.appId
                }, parentNode);
            } else {
                this.dicTable.addNode({dicId: this.idx_++, isAdd: true, appId: this.curApp.appId});
            }
            this.$forceUpdate()
        },
        flagI18(name){
            if(!name){
                return true
            }
            try {
                let i18Name = JSON.parse(name);
                if(!i18Name[this.i18nCurrent].trim()){
                    return  true
                }
            }catch(e){
                if(!name.trim()){
                    return  true
                }
            }
            return false

        },
        getCurrentI18n(){
            this.i18nCurrent= window.localStorage.getItem("language");
            if(!this.i18nCurrent){
                this.i18nCurrent=this.i18nDefault;
            }

        },
        onSave(record) {
            var parentNode = this.dicTable.getParentNode(record);
            if (parentNode && parentNode.isAdd) {
                return;
            }
            let self_ = this;
            if (!this.curTree.treeId) {
                this.$message.error(this.i18n('isMsg.leftTree','请选择左树！'));
                return;
            }
            let message=this.i18n('isMsg.needFill','请填写正确项名或项值')
           if(!(record.name && record.name.trim()) || !(record.value&&record.value.trim()) || this.flagI18(record.name)){
                this.$message.warn(message);
                return ;
            }


            if (record.isAdd) {
                record['dicId'] = "";
                let appId = this.curApp.appId;
                if (appId) {
                    record.appId = appId;
                }
            }


            let errorList = this.dicTable.findNodes(function (data) {
                if (data['value'] == record['value']) return true;
            })
            if(errorList.length>1){
                for(let i=0;i<errorList.length;i++){
                    errorList[i].errorStatus=true;
                }
                this.errorList=errorList;
                this.$message.warning(this.i18n('isMsg.dictionary','字典值[')+record['value']+this.i18n('isMsg.alreadyExists',']已存在!'));
                return;
            }
            for(let i=0;i<this.errorList.length;i++){
                this.errorList[i].errorStatus=false;
            }
            SysDicApi.rowSave({treeId: this.curTree.treeId, data: JSON.stringify(record)}).then(res => {
                let children = record.children;
                if (children) {
                  children.forEach(item=>{
                    item.parentId = res.data.pkId;
                  })
                }
                self_.dicTable.updateNode(record,{isAdd:false,...res.data,children:children});
            })
        },
        parseRows(rows) {
            let appId = this.curApp.appId;
            for (var i = 0; i < rows.length; i++) {
                if (rows[i].isAdd) {
                    rows[i]['dicId'] = "";
                    if (appId) {
                        rows[i]['appId'] = appId;
                    }
                }
                if (rows[i].children) {
                    this.parseRows(rows[i].children);
                }
            }
        },
        onSaveDic() {
            let self_ = this;
            if (!this.curTree.treeId) {
                this.$message.error(this.i18n('isMsg.leftTree','请选择左树！'));
                return;
            }
            var rows = this.dicTable.treeData;
            let message=this.i18n('isMsg.needFill','请填写正确项名或项值')
            for(let i=0;i<rows.length;i++){
                let record=rows[i];
                var flag = true
                if (!this.validData(record,flag)){
                    this.$message.warn(message);
                    return;
                }
                let errorList = this.dicTable.findNodes(function (data) {
                    if (data['value'] == record['value']) return true;
                })
                if(errorList.length>1){
                    for(let i=0;i<errorList.length;i++){
                        errorList[i].errorStatus=true;
                    }
                    this.$forceUpdate();
                    this.errorList=errorList;
                    this.$message.warning('字典值['+record['value']+']已存在!');
                    return;
                }
            }
            for(let i=0;i<this.errorList.length;i++){
                this.errorList[i].errorStatus=false;
            }
            this.parseRows(rows);

            SysDicApi.batchSave({
                treeId: this.curTree.treeId,
                gridData: JSON.stringify(rows)
            }).then(res => {
                self_.handSelect(self_.curTree);
            })
        },
        /**
         * 校验是否有空值
         */
        validData(record,flag){
            if(!(record.name && record.name.trim()) || !(record.value && record.value.trim()) || this.flagI18(record.name)){
                flag = false
                return flag;
            }
            if (record.children && record.children.length > 0 ) {
                let children = record.children;
                let errorList = children.filter(item => !(item.name && item.name.trim()) || !(item.value && item.value.trim()) || this.flagI18(record.name))
                if (errorList && errorList.length > 0){
                    flag = false
                    return flag;
                }
                for (var item of children) {
                    flag = this.validData(item,flag)
                }
            }
            return flag;
        },
        onRemoveDic() {
            var rows = this.dicTable.getSelectedNodes();
            if (rows.length == 0) {
                this.$message.error(this.i18n('isMsg.deleteData','请选择删除的数据项！'));
                return;
            }
            let self_ = this;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips','操作提示'),
                content: this.$ti18('rxMsa.delInfo','您确定需要删除选中的记录吗？'),
                okText: this.$ti18('rxForm.ackBtn','确认'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    let ids = [];
                    for (let i = 0; i < rows.length; i++) {
                        if (!rows[i].isAdd) {
                            ids.push(rows[i].dicId);
                        }
                    }
                    let {selectedRows} = self_.dicTable.$refs['table'];
                    if (ids.length == 0) {
                        self_.dicTable.removeNodes(selectedRows);
                        return;
                    }
                    SysDicApi.delByDicIds(ids.join(','), self_.curTree.treeId).then(res => {
                        self_.dicTable.removeNodes(selectedRows);
                    })
                },
                onCancel() {}
            })
        },
        genQuerySql() {
            if (!this.curTree.treeId) {
                this.$message.error(this.i18n('isMsg.leftTree','请选择左树！'));
                return;
            }
            Util.open({
                component: SysDicSql,
                curVm: this,
                widthHeight: ['1024px', '600px'],
                title: this.i18n('form.sqlStatement','SQL查询语句'),
                data: {
                    nodeAlias: this.curTree.alias
                }
            }, function (action) {

            });
        },
        doDeployMenu() {
            if (!this.curTree.treeId) {
                this.$message.error(this.i18n('isMsg.leftTree','请选择左树！'));
                return;
            }
            var component = "modules/system/SysDicView/SysDicView.vue";
            DialogBox.openDeploymenuDialog({
                name: this.curTree.name?this.curTree.name.replace(/\([^()]*\)/g, ''):"",//去掉括号及内容
                key: this.curTree.alias + 'Dic',
                component: component,
                params: {alias: this.curTree.alias},
                curAppObj:this.curApp

            }, {
                curVm: this, widthHeight: ['800px', '600px'],
            })
        },
        doExport(isSelected) {
            var exportList = [];
            if (isSelected == "1") {
                exportList = this.dicTable.getSelectedNodes();
                ;
                if (!exportList || exportList.length == 0) {
                    this.$warning({
                        title: this.$ti18('rxMsa.masWarn.delInfo','警告'),
                        content: this.i18n('isMsg.expMsg','请选择需要导出的记录！'),
                    });
                    return;
                }
            } else {
                exportList = this.dicTable.getData();
            }

            if (exportList == "") {
                this.$warning({
                    title: this.$ti18('rxMsa.masWarn.delInfo','警告'),
                    content: this.i18n('isMsg.noData','该分类没有数据！'),
                });
                return;
            }

            var solutionIds = [];
            if (isSelected == "1") {
                exportList.forEach(item => {
                    solutionIds.push(item.dicId);
                });
            }else {
                this.getAllDicId(exportList,solutionIds)
            }
            SysDicApi.doExport(solutionIds);
        },
        getAllDicId(exportList,solutionIds){
            exportList.forEach(item => {
                solutionIds.push(item.dicId);
                if (item.children && item.children.length > 0){
                    this.getAllDicId(item.children,solutionIds);
                }
            });
        },
        doImport() {
            Util.open({
                component: FormImport,
                curVm: this,
                widthHeight: ['800px', '600px'],
                title: this.i18n('form.dataDictionaryImport','数据字典导入'),
                data: {
                    treeId: this.curTree.treeId || "",
                    callback: function (params) {
                        let self = this;
                        SysDicApi.doImport(params).then(res => {
                            this.isSpinning = false;
                            if (!res.success) {
                                return;
                            }
                            //self.$message.info(this.i18n('form.importOk','导入成功！'));
                            self.getUpdataSqls(res.data);
                        });
                    }
                }
            }, function (action) {
            });
        },
        //风格化
        styleName(record){
            if(!record.colorConfigs){
                return
            }
            let style = JSON.parse(record.colorConfigs);
            return {
                background:style.bgcolor,
                color:style.fgcolor,
            };
        },
        styleShow(record){
            if(!record.colorConfigs){
                return false
            }
            let style = JSON.parse(record.colorConfigs);
            if(style.bgcolor || style.fgcolor){
                return true
            }
            return  false
        }
    }
}
</script>
<style scoped>
.rx-colorConfigs{
    display: flex;
    height: 34px;
    align-items: center;
    width: 100%;
    border: 1px solid #dadde0;
    border-radius: 5px;
}
.rx-colorConfigs-name{
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    height: 34px;
    display: flex;
    align-items: center;
    border-right: 1px solid #dadde0;
    padding-left: 5px;
}
.rx-colorConfigs-name span{
    padding: 0px 8px;
    height: 20px;
    line-height: 20px;
    border-radius: 3px;
    font-size: 12px;
    flex: 1;
    margin-right: 5px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.rx-colorConfigs-select{
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}
.rx-colorConfigs-select:hover{
    color: #2387fa;
}
.rx-colorConfigs-name:hover .rx-colorConfigs-delete{
    display: block;
    color: #f66767;
    cursor: pointer;
}
.rx-colorConfigs-delete{
    font-size: 16px;
    display: none;
    margin:0px 5px;
}

</style>
